package myapp.com.xm.myapplication.Adapter;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

public class ViewHolder extends RecyclerView.ViewHolder {
    //用来存放view减少findviewByid的次数
    private SparseArray<View> mViews;
    public ViewHolder(@NonNull View itemView) {
        super(itemView);
        mViews = new SparseArray<>();
    }

    /**
     * 设置TextView文本
     * @param viewId
     * @param text
     * @return
     */
    public ViewHolder setText(int viewId,CharSequence text){
        TextView tv = getView(viewId);
        tv.setText(text);
        return this;
    }

    public <T extends View> T getView(int viewId){
        View view = mViews.get(viewId);
        if (view == null){
            view = itemView.findViewById(viewId);
            mViews.put(viewId,view);
        }

        return (T)view;
    }

    /**
     * 设置view是否可见
     * @param viewId
     * @param visibility
     * @return
     */
    public ViewHolder setViewVisibility(int viewId,int visibility){
        getView(viewId).setVisibility(visibility);
        return this;
    }

    /**
     * 设置ImageView资源
     * @param viewId
     * @param resId
     * @return
     */
    public  ViewHolder setImageResourse(int viewId,int resId){
        ImageView imageView = getView(viewId);
        imageView.setImageResource(resId);
        return this;
    }

    /**
     * 设置条目的点击事件
     * @param listener
     */
    public void setOnItemClickListener(View.OnClickListener listener){
        itemView.setOnClickListener(listener);
    }

    /**
     * 设置图片通过url,加载图片使用的第三方可能不一样，所以定义了HolderImageLoader
     * @param viewId
     * @param imageLoader
     */
    public void setImageByUrl(int viewId,HolderImageLoader imageLoader){
        ImageView imageView = getView(viewId);
        if (imageLoader == null){
            throw  new NullPointerException("imageLoader is null！");
        }
        imageLoader.displayImage(imageView.getContext(),imageView,imageLoader.getImagePath());
    }
    /**
     * 设置条目的长按事件
     * @param listener
     */
    public void setOnItemLongClickListener(View.OnLongClickListener listener){
        itemView.setOnLongClickListener(listener);
    }

    public static abstract class HolderImageLoader{
        private String mImagePath;
        public HolderImageLoader(String imagePath){
            this.mImagePath = imagePath;
        }
        public String getImagePath(){
            return mImagePath;
        }

        public abstract void displayImage(Context context, ImageView imageView, String imagePath);
    }
}
